#pragma once

#include <iostream>
#include <cstring>
#include <cerrno>
#include <sys/epoll.h>
#include "Log.hpp"
#include "err.hpp"

static const int gnum = 128;

static const int epfd = -1;

class Epoll
{
public:
    Epoll()
        :_epfd(epfd)
    {
    }

    void creat()
    {
        _epfd = epoll_create(gnum);
        if (_epfd < 0)
        {
            LogMessage(Error, "epoll_create fail,%s,%d", strerror(errno), errno);
            exit(EPOLL_CREATE_ERR);
        }
        LogMessage(Debug, "epoll_create success");
    }

    int wait(epoll_event *events, int MaxEvents, int timeout)
    {
        return epoll_wait(_epfd, events, MaxEvents, timeout);
    }

    void AddEvent(int fd,uint32_t event)
    {
        struct epoll_event Event;
        Event.events = event;
        Event.data.fd = fd;
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, fd, &Event);
        if (n < 0)
        {
            LogMessage(Error, "EPOLL_CTL_ADD_ERR fail,%s,%d", strerror(errno), errno);
            exit(EPOLL_CTL_ADD_ERR);
        }
        LogMessage(Debug, "epoll_ctl success");
    }

    void DeleteEvent(int fd)
    {
        int n = epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
        if (n < 0)
        {
            LogMessage(Error, "EPOLL_CTL_ADD_ERR fail,%s,%d", strerror(errno), errno);
            exit(EPOLL_CTL_ADD_ERR);
        }
        LogMessage(Debug, "epoll_ctl success");
    }

    int Fd()
    {
        return _epfd;
    }

    void Close()
    {
        if(_epfd != epfd) close(_epfd);
    }

    ~Epoll()
    {
    }

private:
    int _epfd;
};